package com.sudo.api._admin;

import com.sudo.common.annotation.ApiIdempotent;
import com.sudo.common.annotation.ApiAuthorization;
import com.sudo.common.constant.SysConfigConstant;
import com.sudo.common.enums.SysYesNo;
import com.sudo.common.utils.HttpUserInfoUtil;
import com.sudo.common.utils.JsonRes;
import com.sudo.common.utils.LocalDateTimeUtil;
import com.sudo.common.utils.PagedGridResult;
import com.sudo.dao.admin.entity.SysAutoRole;
import com.sudo.dao.admin.entity.SysConfig;
import com.sudo.dao.admin.entity.SysUser;
import com.sudo.dao.admin.model.bo.SysAutoRoleQueryBO;
import com.sudo.dao.admin.model.bo.SysAutoRoleUpdateBO;
import com.sudo.service.admin.service.SysAutoRoleService;
import com.sudo.service.admin.service.SysConfigService;
import com.sudo.service.admin.service.SysRoleService;
import com.sudo.service.admin.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Slf4j
@Api(value = "用户角色自动化",tags = {"用户角色自动化相关的接口"})
@RestController
@RequestMapping("sysAutoRole")
public class SysAutoRoleController extends AdminBaseController {

    @Resource
    private SysAutoRoleService sysAutoRoleService;

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysConfigService sysConfigService;

    @Resource
    private SysRoleService sysRoleService;

    @ApiOperation(value = "分页查询注册用户",httpMethod = "POST")
    @PostMapping("/queryAutoRoleByPage")
    public JsonRes queryAutoRoleByPage(@RequestBody SysAutoRoleQueryBO sysAutoRoleQueryBO, HttpServletRequest request) {

        PagedGridResult pagedGridResult = sysAutoRoleService.queryAutoRoleByPage(sysAutoRoleQueryBO);
        return JsonRes.ok(pagedGridResult);
    }

    @ApiOperation(value = "根据用户名查询注册用户",httpMethod = "GET")
    @GetMapping("/getAutoRoleByUsername")
    public JsonRes getAutoRoleByUsername(@RequestParam String username, HttpServletRequest request) {

        SysAutoRole sysAutoRole = sysAutoRoleService.getAutoRoleByUsername(username);
        return JsonRes.ok(sysAutoRole);
    }

    @ApiIdempotent
    @ApiAuthorization(menu = "auto_role",button = "update")
    @ApiOperation(value = "根据用户名修改用户自动化",httpMethod = "POST")
    @PostMapping("/updateAutoRole")
    public JsonRes updateAutoRole(@RequestBody @Validated SysAutoRoleUpdateBO sysAutoRoleUpdateBO,
                                  BindingResult result) {
        if (result.hasErrors()) {
            return JsonRes.errorMsg(getFirstError(result));
        }
        if (superName(sysAutoRoleUpdateBO.getUsername())) {
            return JsonRes.errorMsg("禁止修改超级管理员");
        }
        // 设置的角色不能是超级管理员
        if (superAdmin(sysAutoRoleUpdateBO.getSetupRole())) {
            return JsonRes.errorMsg("设定角色不能是超级管理员");
        }
        if (superAdmin(sysAutoRoleUpdateBO.getExpiryRole())) {
            return JsonRes.errorMsg("过期角色不能是超级管理员");
        }
        // 设置的角色必须存在
        boolean hasSetupRole = sysRoleService.hasRoleCode(sysAutoRoleUpdateBO.getSetupRole());
        if (!hasSetupRole) {
            return JsonRes.errorMsg("设定角色不存在");
        }
        boolean hasExpiryRole = sysRoleService.hasRoleCode(sysAutoRoleUpdateBO.getExpiryRole());
        if (!hasExpiryRole) {
            return JsonRes.errorMsg("过期角色不存在");
        }

        SysUser sysUser = sysUserService.getSysUserWithoutPwdByUsername(sysAutoRoleUpdateBO.getUsername());
        LocalDateTime createTime = LocalDateTimeUtil.convertStr2LocateDateTime(
                sysUser.getCreateTime(),LocalDateTimeUtil.yyyy_MM_dd_HH_mm_ss);
        LocalDateTime expiredTime = sysAutoRoleUpdateBO.getExpirationTime().withSecond(0);
        if (expiredTime.minusMinutes(10).compareTo(createTime) < 0) {
            return JsonRes.errorMsg("至少比用户创建时间大10分钟");
        }

        int affectCount = sysAutoRoleService.updateAutoRole(sysAutoRoleUpdateBO,sysUser.getStatus());
        return JsonRes.judge(affectCount);
    }

    @ApiOperation(value = "根据用户名查询用户过期信息",httpMethod = "GET")
    @GetMapping("/getMyExpirationInfo")
    public JsonRes getMyExpirationInfo(HttpServletRequest request) {
        String sessionUser = HttpUserInfoUtil.getSessionUser(request);
        SysAutoRole sysAutoRole = sysAutoRoleService.getAutoRoleByUsername(sessionUser);
        SysUser sysUser = sysUserService.getSysUserWithoutPwdByUsername(sessionUser);
        SysConfig sysConfig = sysConfigService.getSysConfigByObjectKey(SysConfigConstant.USER_REGIST, "expiry_tip_time");
        String expirationTimeStr = LocalDateTimeUtil.convertLocateDateTime2Str(sysAutoRole.getExpirationTime(), LocalDateTimeUtil.yyyy_MM_dd_HH_mm_ss);
        if (SysYesNo.YES.name().equals(sysAutoRole.getIsExpired())) {
            return JsonRes.okMsg("<span style=\"color:red;font-weight:bold;\">当前用户已过期，部分权限不可用，过期时间："+ expirationTimeStr +"</span>");
        }else {
            LocalDateTime createTime = LocalDateTimeUtil.convertStr2LocateDateTime(sysUser.getCreateTime(),LocalDateTimeUtil.yyyy_MM_dd_HH_mm_ss);
            LocalDateTime expirationTime = sysAutoRole.getExpirationTime();
            Integer expiryTipTime = Integer.parseInt(sysConfig.get_value());    //过期剩余时间提示
            int i = expirationTime.minusMinutes(expiryTipTime).compareTo(createTime);
            if (i<=0){
                return JsonRes.okMsg("<span style=\"color:red;font-weight:bold;\">当前用户即将过期，过期时间："+ expirationTimeStr +"</span>");
            }
        }
        return JsonRes.okMsg("<span style=\"color:green;font-weight:bold;\">当前用户过期时间："+ expirationTimeStr +"</span>");
    }

}
